package com.cxs.xiaomi.service.impl;

import com.cxs.xiaomi.dao.AddressDao;
import com.cxs.xiaomi.dao.impl.AddressDaoImpl;
import com.cxs.xiaomi.domain.Address;
import com.cxs.xiaomi.service.AddressService;
import cxs.utils.JdbcUtil;

import java.sql.SQLException;
import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/9/15  11:12
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
public class AddressServiceImpl implements AddressService {

    private AddressDao addressDao = new AddressDaoImpl();
    @Override
    public List<Address> getList(Integer userId) {
        return addressDao.selectByUserId(userId);
    }

    @Override
    public boolean update(Address address) {
        return addressDao.updateAllById(address) > 0;
    }

    @Override
    public boolean deleteAddr(String id) {
        return addressDao.deleteById(Integer.parseInt(id)) > 0;
    }

    @Override
    public boolean serDefaultAddr(String id) {
        try {
            JdbcUtil.begin();
            int i = addressDao.updateLevelById(Integer.parseInt(id));
            int n = addressDao.updateOtherLevelByNotId(Integer.parseInt(id));
            if(i > 0 && n > 0){
                JdbcUtil.commit();
                return true;
            }
            JdbcUtil.commit();
            return false;
        } catch (SQLException e) {
            try {
                e.printStackTrace();
                JdbcUtil.commit();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }finally {
            try {
                JdbcUtil.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public boolean addAddr(Address address) {
        return addressDao.insert(address) > 0;
    }

    @Override
    public Address getAddr(Integer aid) {
        return addressDao.selectById(aid);
    }

    @Override
    public List<Address> getList(String name) {
        return addressDao.selectByName(name);
    }
}
